<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\middleware;

use Closure;
use think\Config;
use think\facade\Log;
use think\Request;
use think\Response;

/**
 * 跨域请求支持
 */
class AllowCrossDomain
{
    protected mixed $cookieDomain;

    protected array $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age' => 1800,
        'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,Token',
    ];

    public function __construct(Config $config)
    {
        $this->cookieDomain = $config->get('cookie.domain', '');
    }

    /**
     * 允许跨域请求
     * @access public
     * @param Request $request
     * @param Closure $next
     * @param array|null $header
     * @return Response
     */
    public function handle(Request $request, Closure $next, ?array $header = []): Response
    {
        // 增加日志记录
        $traceId = $GLOBALS['YMS_TRACEID'] ?? '';
        Log::info("\n============ TRACEID $traceId ==============");
        Log::info($_SERVER['REQUEST_METHOD'] . ': ' . getUrl());
        Log::info('REFERER: ' . ($_SERVER['HTTP_REFERER'] ?? 'NO REFERER'));
        Log::info('GET: ' . json_encode($_GET, JSON_UNESCAPED_UNICODE));
        Log::info('POST: ' . json_encode($_POST, JSON_UNESCAPED_UNICODE));
        Log::info('COOKIE: ' . json_encode($_COOKIE, JSON_UNESCAPED_UNICODE));
        Log::info('PARAM: ' . json_encode(input('param.'), JSON_UNESCAPED_UNICODE));
        Log::info('- - - - - - - - - - - - - -');
        
        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;

        if (!isset($header['Access-Control-Allow-Origin'])) {
            $origin = $request->header('origin');

            if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
        }
        
        $header['Trace-Id'] = $traceId;

        return $next($request)->header($header);
    }
}
